import React, { useEffect, useState } from 'react';
import { message, Space, Card, Tabs, Button } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { connect, Dispatch, history } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { CQ_DETAIL } from '@/actions/cq';
import { WORKBENCH_INIT, FETCH_CQUNDOTASK, FETCH_TRADEUNDOTASK, TRADE_TASK_HIS, HANDLE_TRADE_TASK, 
  WORKBENCH_UNMOUNT } from '@/actions/workbench';
import { AGrid } from '@/components/SelfComp';
import { ConnectState } from '@/models/connect';
import { DataItem } from '@/types/global';
import { CqUndoTaskType, TradeTaskHandleFormValue, TradeTaskHandleRecord, TradeUndoTaskType, 
  TradeTaskConfirmType, UndoTaskQueryParams, CqDetailInfo } from '@/types/workbench';
import { getCurrentLoginUser } from '@/utils/authority';
import { getItemValue } from '@/utils/commons';
import { getDateTime } from '@/utils/utils';
import { WorkbenchStatisticsCard, TradeTaskConfirmModal } from './components';

interface WorkbenchProps {
  dispatch: Dispatch;
  cqUndoTaskList: CqUndoTaskType[];
  tradeUndoTaskList: TradeUndoTaskType[];
  // 需求待办任务总数
  cqUndoTaskNum: number;
  // 交易待办任务总数
  tradeUndoTaskNum: number;
  // 今日已完成需求任务总数
  todayCqDoTaskNum: string;
  // 今日已完成交易任务总数
  todayTradeDoTaskNum: string;
  cqUndoTaskTotal: string;
  tradeUndoTaskTotal: string;
  cqTaskCurrentPageNum: string,
  tradeTaskCurrentPageNum: string,
  pageSize: string;
  cqUndoTaskLoading: boolean;
  tradeUndoTaskLoading: boolean;
  taskHandleLoading: boolean;
  cqUndoTaskTypeData: DataItem[];
  tradeUndoTaskTypeData: DataItem[];
  developerData: DataItem[];
  testerData: DataItem[];
}

const EMPTY_TRADE_TASK: TradeUndoTaskType = {
  taskId: '',
	taskName: '',
	taskCreateTime: '',
	status: '',
	actInstId: '',
	actTaskId: '',
  taskType: '',
  funcCode: '',
  cqCode: '',
  startDate: '',
  endDate: '',
  developer: '',
  tester: '',
  comment: ''
}

const EMPTY_CONFIRM: TradeTaskConfirmType = {
  funcCode: '',
  status: '',
  taskName: '',
  developer: '',
  tester: '',
  comment: '',
  startDate: '',
  endDate: '',
  hisList: []
}

/**
 * 工作台
 */
const Workbench: React.FC<WorkbenchProps> = (props) => {

  const [currentTabKey, setCurrentTabKey] = useState<string>('cqUndoTask');
  const [taskConfirmFormData, setTaskConfirmFormData] = useState<TradeTaskConfirmType>(EMPTY_CONFIRM);
  const [tradeTaskConfirmModalVisible, setTradeTaskConfirmModalVisible] = useState<boolean>(false);
  const [tradeTaskRecord, setTradeTaskRecord] = useState<TradeUndoTaskType>(EMPTY_TRADE_TASK);
  // 默认为10
  const [pageSize, setPageSize] = useState<number>(10);
  const pkField = 'actTaskId';

  useEffect(() => {
    console.info('Workbench.useEffect');
    // 查询本页面需所有参数
    // 获取所属系统
    // 获取审核人列表
    fetchWorkbenchInitParams();
    fetchCqUndoTaskList(1, pageSize);
    fetchTradeUndoTaskList(1, pageSize);
    return () => {
      const { dispatch } = props;
      dispatch(WORKBENCH_UNMOUNT({}));
    }
  }, []);

  const cqUndoTaskColumns: ColumnsType<CqUndoTaskType> = [
    {
      title: '操作',
      dataIndex: 'oper',
      align: 'center',
      width: 120,
      render: (_text: string, record: CqUndoTaskType, _index: number) => {
        const { cqUndoTaskTypeData } = props;
        const { status } = record;
        let value = getItemValue(cqUndoTaskTypeData, status);
        if (value === status) {
          return '';
        }
        return <a title={value} onClick={() => cqUndoTaskMenuItemClick(status, record)}>{value}</a>
      },
    },
    {
      title: '需求编号',
      dataIndex: 'cqCode',
      width: 150
    },
    {
      title: '需求名称',
      dataIndex: 'cqName',
      width: 300,
      ellipsis: true
    },
    {
      title: '所属系统',
      dataIndex: 'systemCode',
      width: 120
    },
    {
      title: '所属集群',
      dataIndex: 'clstCode',
      width: 120
    },
    {
      title: '所属应用',
      dataIndex: 'appCode',
      width: 120
    },
    {
      title: '任务名称',
      dataIndex: 'taskName',
      width: 150,
      ellipsis: true
    },
    {
      title: '任务创建时间',
      dataIndex: 'taskCreateTime',
      width: 140,
      ellipsis: true
    },
  ];

  const tradeUndoTaskColumns: ColumnsType<TradeUndoTaskType> = [
    {
      title: '操作',
      dataIndex: 'oper',
      align: 'center',
      width: 120,
      render: (_text: string, record: TradeUndoTaskType, _index: number) => {
        const { tradeUndoTaskTypeData } = props;
        const { status } = record;
        let value = getItemValue(tradeUndoTaskTypeData, status);
        if (value === status) {
          return '';
        }
        return <a title={value} onClick={() => tradeUndoTaskMenuItemClick(status, record)}>{value}</a>
      },
    },
    {
      title: '交易功能码',
      dataIndex: 'funcCode',
      width: 150,
    },
    {
      title: '交易任务名称',
      dataIndex: 'taskName',
      width: 300,
      ellipsis: true
    },
    {
      title: '需求编号',
      dataIndex: 'cqCode',
      width: 150
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      width: 120
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      width: 120
    },
    {
      title: '开发人员',
      dataIndex: 'developer',
      width: 120
    },
    {
      title: '测试人员',
      dataIndex: 'tester',
      width: 120
    },
    {
      title: '任务创建时间',
      dataIndex: 'taskCreateTime',
      width: 140,
      ellipsis: true
    },
  ];

  /**
   * 交易初始化
   */
  const fetchWorkbenchInitParams = () => {
    const { dispatch } = props;
    dispatch(WORKBENCH_INIT({}));
  }

  /**
   * 分页查询需求待办任务
   * @param pageNum 页码
   * @param pageSize 每页记录数
   */
  const fetchCqUndoTaskList = (pageNum: number, pageSize: number) => {
    const userCode = getCurrentLoginUser();
    const { dispatch } = props;
    const params: UndoTaskQueryParams = {
      userCode,
      pageNum,
      pageSize
    }
    dispatch(FETCH_CQUNDOTASK({
      ...params
    }));
  }

  /**
   * 分页查询交易待办任务
   * @param pageNum 页码
   * @param pageSize 每页记录数
   */
  const fetchTradeUndoTaskList = (pageNum: number, pageSize: number) => {
    const userCode = getCurrentLoginUser();
    const { dispatch } = props;
    const params: UndoTaskQueryParams = {
      userCode,
      pageNum,
      pageSize
    }
    dispatch(FETCH_TRADEUNDOTASK({
      ...params
    }));
  }

  /**
   * 需求代办任务点击函数
   * @param key 菜单key
   * @param record 菜单所在表格记录行
   */
  const cqUndoTaskMenuItemClick = async (key: string, record: CqUndoTaskType) => {
    console.info('menuItemClick', key, record);
    // console.info('cqUndoTaskTableHandler');
    const { status } = record;
    let url = '404';
    switch(status)
    {
      case '1':
        // 录入需求详细信息
        url = '/workbench/task/fillCqDetailInfo';
        break;
      case '2':
        // 录入文档信息
        url = '/workbench/task/fillCqDocInfo';
        break;
      case '3':
        // 分配交易
        url = '/workbench/task/allotCqTrade';
        break;
      default:
        // 404
        url = '404'
    }
    if (url === '404') {
      message.warn('任务状态非法，请联系管理员');
      return;
    }
    // 查询需求详细信息
    const { cqId } = record;
    const { dispatch } = props;
    const res = await dispatch(CQ_DETAIL({
      cqId,
      status
    }));
    // console.info(res);
    if (res) {
      const { result } = res;
      // console.info(result);
      // 需求详细信息
      const { tradeList, ...resProps } = result;
      const cqDetailInfo: CqDetailInfo = {
        ...resProps
      }
      if (tradeList) {
        history.push({
          pathname: url,
          // query: {
          //   e
          // },
          state: {
            cqDetailInfo,
            cqUndoTaskInfo: record,
            tradeList
          }
        });
      } else {
        history.push({
          pathname: url,
          // query: {
          //   e
          // },
          state: {
            cqDetailInfo,
            cqUndoTaskInfo: record,
          }
        });
      }
    }
  }

  /**
   * 交易代办任务点击函数
   * @param key 菜单key
   * @param record 菜单所在表格记录行
   */
  const tradeUndoTaskMenuItemClick = (key: string, record: TradeUndoTaskType) => {
    // console.info('menuItemClick', key, record);
    // console.info('tradeUndoTaskTableHandler');
    // console.info(record);
    setTradeTaskRecord(record);
    openTradeTaskConfirmModal(record);
  }

  /**
   * 打开交易任务确认窗口，打开前先查询是否存在历史确认记录
   */
  const openTradeTaskConfirmModal = async (record: TradeUndoTaskType) => {
    const { taskId } = record;
    // 需要查询出任务的历史记录
    // 查询成功，才会弹窗
    const { dispatch } = props;
    const res = await dispatch(TRADE_TASK_HIS({
      taskId
    }));
    // console.info(res);
    if (res) {
      const { hisList } = res;
      const { funcCode, taskName, developer, tester, startDate, endDate, comment, status } = record;
      const formData: TradeTaskConfirmType = {
        funcCode,
        status,
        taskName,
        developer,
        tester,
        comment,
        startDate,
        endDate,
        hisList
      };
      setTaskConfirmFormData(formData);
      setTradeTaskConfirmModalVisible(true);
    }
  }

  /**
   * 页面统计数据面板点击函数
   * @param boxType 面板类型，对应下方不同Tab的页签
   */
  const cardClick = (boxType: string) => {
    console.info('Workbench.onClick', boxType, currentTabKey);
    changeTabs(boxType);
  }

  /**
   * 切换TAB页
   */
  const changeTabs = (key: string) => {
    // 改变Tab
    // console.log(`changeTabs=${key}`);
    if (key !== currentTabKey) {
      setCurrentTabKey(key);
      setPageSize(10);
      // 重新查询
    }
  }

  /**
   * 刷新任务按钮事件
   */
  const refreshUndoTaskList = () => {
    fetchCqUndoTaskList(1, pageSize);
    fetchTradeUndoTaskList(1, pageSize);
  }

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    // console.log(page, pageSize);
    if (currentTabKey === 'cqUndoTask') {
      setPageSize(pageSize);
      fetchCqUndoTaskList(page, pageSize);
    } else if (currentTabKey === 'tradeUndoTask') {
      setPageSize(pageSize);
      fetchTradeUndoTaskList(page, pageSize);
    }
  };

  /**
   * 确认任务，驳回任务，只有通讯成功才会关闭窗口
   */
  const handleTradeTaskConfirmModalOk = (record: TradeTaskHandleFormValue) => {
    // console.info('handleTradeTaskConfirmModalOk', record);
    // 异步
    tradeTaskHandler(record);
  }

  /**
   * 使用await直接调用service
   * @param {*} record 数据
   * @returns 交易任务处理结果
   */
  const tradeTaskHandler = async (record: TradeTaskHandleFormValue) => {
    if (!tradeTaskRecord || !tradeTaskRecord.cqCode) {
      message.warn('任务数据非法，无法处理');
      return;
    }
    const { status, taskId, actInstId, actTaskId } = tradeTaskRecord;
    const userCode = getCurrentLoginUser();
    const { dispatch } = props;
    const payload: TradeTaskHandleRecord = {
      ...record,
      userCode,
      status,
      taskId,
      actInstId,
      actTaskId
    }
    const res = await dispatch(HANDLE_TRADE_TASK({
      ...payload
    }));
    console.info(res);
    if (res) {
      const { agree } = record;
      if (agree) {
        message.info('任务确认成功');
      } else {
        message.info('任务驳回成功');
      }
      setTradeTaskConfirmModalVisible(false);
      // 重新查询
      fetchTradeUndoTaskList(1, pageSize);
    }
  }

  /**
   * 弹窗取消事件，无动作，仅清空弹窗数据
   */
  const handleTradeTaskConfirmModalCancel = () => {
    // console.info('handleTradeTaskModalCancel');
    setTradeTaskConfirmModalVisible(false);
  }

  /**
   * 创建需求待办任务表格
   * 
   * @param props 
   * @returns 
   */
  const CreateCqUndoTaskTable = (props: WorkbenchProps) => {
    const { cqUndoTaskList, cqUndoTaskNum, cqUndoTaskLoading } = props;
    const cqUndoTaskCode = 'cqUndoTask';
    const cqUndoRowKey = (record: CqUndoTaskType) => record.actTaskId;
    return {
      label: '需求待办任务',
      key: cqUndoTaskCode,
      children: (
        <AGrid
          code={cqUndoTaskCode}
          noActionColumn={true}
          columns={cqUndoTaskColumns}
          rowKey={cqUndoRowKey}
          pkField={pkField}
          dataSource={cqUndoTaskList}
          loading={cqUndoTaskLoading}
          total={cqUndoTaskNum}
          onPageNumAndSizeChange={onPageNumAndSizeChange}
          scroll={{x:1300}}
        />
      )
    }
  }
  
  /**
   * 创建交易待办任务表格
   * 
   * @param props 
   * @returns 
   */
  const CreateTradeUndoTaskTable = (props: WorkbenchProps) => {
    const { tradeUndoTaskList, tradeUndoTaskNum, tradeUndoTaskLoading } = props;
    const tradeUndoTaskCode = 'tradeUndoTask';
    const tradeUndoRowKey = (record: TradeUndoTaskType) => record.actTaskId;
    return {
      label: '交易待办任务',
      key: tradeUndoTaskCode,
      children: (
        <AGrid
          code={tradeUndoTaskCode}
          noActionColumn={true}
          columns={tradeUndoTaskColumns}
          rowKey={tradeUndoRowKey}
          pkField={pkField}
          dataSource={tradeUndoTaskList}
          loading={tradeUndoTaskLoading}
          total={tradeUndoTaskNum}
          onPageNumAndSizeChange={onPageNumAndSizeChange}
          scroll={{x:1300}}
        />
      )
    }
  }

  // 需求任务数据
  const { cqUndoTaskNum, cqUndoTaskLoading } = props;
  // 交易任务数据
  const { tradeUndoTaskNum, tradeUndoTaskLoading, taskHandleLoading } = props;
  const { developerData, testerData, tradeUndoTaskTypeData } = props;
  const dateTimeStr = getDateTime();
  // Tabs页签
  const items = [
    CreateCqUndoTaskTable(props),
    CreateTradeUndoTaskTable(props)
  ];

  return (
    <PageContainer
      extra={dateTimeStr}
    >
      <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
        <WorkbenchStatisticsCard
          cqUndoTaskNum={cqUndoTaskNum}
          todayCqDoTaskNum={0}
          tradeUndoTaskNum={tradeUndoTaskNum}
          todayTradeDoTaskNum={0}
          cqTaskLoading={cqUndoTaskLoading}
          tradeTaskLoading={tradeUndoTaskLoading}
          onClick={cardClick}
        />
        <Card title='待办任务列表'
          extra={<Button type='link' onClick={() => refreshUndoTaskList()}>刷新任务</Button>}
        >
          <Tabs
            defaultActiveKey='cqUndoTask'
            onChange={changeTabs}
            activeKey={currentTabKey}
            items={items}
          />
        </Card>
      </Space>
      {
        !tradeTaskConfirmModalVisible ? null :
        <TradeTaskConfirmModal
          colon={false}
          modalTitle=''
          modalWidth={1100}
          modalVisible={tradeTaskConfirmModalVisible}
          loading={taskHandleLoading}
          formData={taskConfirmFormData}
          developerData={developerData}
          testerData={testerData}
          tradeUndoTaskTypeData={tradeUndoTaskTypeData}
          onHandlerOK={handleTradeTaskConfirmModalOk}
          onHandlerCancel={handleTradeTaskConfirmModalCancel}
        />
      }
    </PageContainer>
  );
}

export default connect(({ workbenchs, users, loading }: ConnectState) => ({
  ...workbenchs,
  cqUndoTaskTypeData: workbenchs.cqUndoTaskTypeData,
  tradeUndoTaskTypeData: workbenchs.tradeUndoTaskTypeData,
  developerData: users.developerData,
  testerData: users.testerData,
  cqUndoTaskLoading: loading.effects['workbenchs/queryCqUndoTaskList'],
  tradeUndoTaskLoading: loading.effects['workbenchs/queryTradeUndoTaskList'],
  taskHandleLoading: loading.effects['workbenchs/handleTradeTask'],
}))(Workbench);